<?php
namespace app\admin\controller;

use app\common\model\AdminMenuModel;
use app\common\model\AdminRoleModel;
use think\facade\Log;

/**
 * 后台管理
 */
class Index extends Common
{
    /**
     * 首页
     * @author 贺强
     * @time   2018-10-25 14:13:15
     */
    public function index()
    {
        $admin = $this->is_login(0);
        if ($admin) {
            $modular = $this->get_menus($admin['role_id'], 1);
            $menu = $this->get_menus($admin['role_id']);
            $where = ['is_delete' => 0];
            $list = AdminMenuModel::getList($where, ['identity', 'title', 'modular', 'url']);
            $list1 = array_column($list, null, 'identity');
            $menu_str = json_encode($list1);
            $list2 = array_column($list, 'modular', 'identity');
            $modular_str = json_encode($list2);
            return view('index', compact('admin', 'modular', 'menu', 'menu_str', 'modular_str'));
        }
        $this->redirect('/login/index3');
        exit;
    }

    /**
     * 根据用户角色 ID 获取该用户的权限
     * @author 贺强
     * @time   2018-10-25 14:13:07
     * @param integer $role_id 用户角色 ID
     * @param integer $modular 是否查询模块
     * @return array 返回该用户拥有权限菜单
     */
    private function get_menus($role_id = 0, $modular = 0)
    {
        $where = [['is_delete', '=', 0], ['is_hide', '=', 0]];
        if ($role_id !== '1') {
            $menus = AdminRoleModel::getFieldValue('menus', ['id' => $role_id]);
            $menu_ids = explode(',', $menus);
            if (!empty($menu_ids)) {
                $where[] = ['id', 'in', $menu_ids];
            } else {
                $where[] = ['id', '=', 0];
            }
        }
        if ($modular) {
            $where[] = ['modular', '=', ''];
        } else {
            $where[] = ['modular', '<>', ''];
        }
        $list = AdminMenuModel::getList($where, true, '', ['pid' => 'asc', 'sort' => 'asc']);
        $arr = [];
        foreach ($list as $item) {
            if ($item['pid'] === '') {
                $arr[] = $item;
            } else {
                foreach ($arr as &$item2) {
                    if ($item['pid'] === $item2['id']) {
                        $item2['children'][] = $item;
                        break;
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 后台欢迎页
     * @author 贺强
     * @time   2018-10-25 14:12:59
     */
    public function index_v1()
    {
        return view('index_v2');
    }

    public function write_log()
    {
        Log::info('admin log message');
    }
}
